<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <!--        <el-button type="danger"-->
        <!--                   size="small"-->
        <!--                   icon="el-icon-delete"-->
        <!--                   plain-->
        <!--                   v-if="permission.food_delete"-->
        <!--                   @click="handleDelete">删 除-->
        <!--        </el-button>-->
      </template>
      <template slot-scope="{row}" slot="status">
        <el-tag v-if="row.status === 1" type="success">上 架</el-tag>
        <el-tooltip v-if="row.status === 2" class="item" effect="dark" :content="`下架时间: ${row.downTime}`" placement="top">
          <el-tag type="danger">下 架</el-tag>
        </el-tooltip>
      </template>
      <template slot-scope="{row}" slot="kcal">
        <el-tag type="primary">{{ row.kcal }} kcal</el-tag>
      </template>
      <template slot-scope="{type,disabled}" slot="kcalForm">
        <el-tag>{{ foodKcal }} kcal</el-tag>
      </template>
      <template slot-scope="{type,disabled}" slot="ingredientsForm">
        <div>
          <el-table
            :data="ingredientsTableData"
            border
            style="width: 100%">
            <el-table-column
              label="食材">
              <template slot-scope="scope">
                <el-autocomplete v-model="scope.row.ingredientsName" class="el-input" :fetch-suggestions="queryIngredientsAsync"
                                 placeholder="搜索食材" @select="(val) => handleIngredientsSelect(val, scope.$index)" clearable @change="(val) => handleIngredientsChange(val, scope.$index)"></el-autocomplete>
              </template>
            </el-table-column>
            <el-table-column
              label="克重">
              <template slot-scope="scope">
                <el-input :disabled="scope.row.unit || scope.row.unit !== ''" v-model="scope.row.weight" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="数量">
              <template slot-scope="scope">
                <el-input :placeholder="scope.row.unit !== '' ? unitContent(scope.row.unit) : ''"
                          :disabled="!scope.row.unit || scope.row.unit === ''"
                          v-model="scope.row.unitCount" type="number"
                          @change="handleUnitCountChange(scope.$index, scope.row.unitCount, scope.row.unit)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="kcal">
              <template slot-scope="scope">
                <el-tag>{{ ingredientsKcal(scope.row.weight, scope.row.kcal) }} kcal</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="right">
              <template slot="header" slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleAddItem">添加</el-button>
              </template>
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleRemoveItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-button
          v-if="row.canDelete"
          icon="el-icon-delete"
          type="text"
          size="small"
          @click.stop="rowDel(row)"
        >删 除
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/food/food";
import {getSelect} from "@/api/food/ingredients";
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        column: [
          {
            label: "名称",
            prop: "name",
            rules: [{
              required: true,
              message: "请输入名称",
              trigger: "blur"
            }],
            search: true,
            row: true,
            span: 24
          },
          {
            label: "分类",
            prop: "foodCategoryId",
            rules: [{
              required: true,
              message: "请选择分类",
              trigger: "blur"
            }],
            row: true,
            type: "select",
            dicUrl: '/api/celery-food/food-category/select',
            search: true,
            props: {
              label: "name",
              value: "id"
            },
            span: 24
          },
          {
            label: "需要食材",
            prop: "ingredients",
            formslot: true,
            hide: true,
            row: true,
            span: 24
          },
          {
            label: "热量",
            prop: "kcal",
            formslot: true,
            slot: true,
            disabled: true,
            row: true,
            span: 24
          },
          {
            label: "排序",
            prop: "sort",
            rules: [{
              required: true,
              message: "请输入名称",
              trigger: "blur"
            }],
            value: 99,
            type: "number",
            row: true,
            span: 24
          },
          {
            label: "是否上架",
            prop: "status",
            type: "switch",
            slot: true,
            value: 1,
            dicData: [
              {
                label: '下架',
                value: 2
              },
              {
                label: '上架',
                value: 1
              }
            ],
            props: {
              label: "label",
              value: "value"
            },
            rules: [{
              required: true,
              message: "请选择是否上架",
              trigger: "blur"
            }],
          },
          {
            label: "占用格数",
            prop: "gridCount",
            type: "radio",
            value: 1,
            dicData: [
              {
                label: '0格',
                value: 0
              },
              {
                label: '1格',
                value: 1
              },
              {
                label: '2格',
                value: 2
              },
              {
                label: '3格',
                value: 3
              },
              {
                label: '4格',
                value: 4
              }
            ],
            props: {
              label: "label",
              value: "value"
            },
            rules: [{
              required: true,
              message: "请输入占用格数",
              trigger: "blur"
            }],
            row: true,
            span: 24
          },
          {
            label: "封面",
            prop: "pictureUrl",
            dataType: 'string',
            type: 'upload',
            listType: 'picture-card',
            propsHttp: {
              res: 'data',
              url: 'link',
              name: 'originalName'
            },
            limit: 9,
            tip: '只能上传jpg/png文件，且不超过500kb, 限制9张图片',
            action: '/api/blade-resource/oss/endpoint/put-file',
            row: true,
            span: 24
          },
          {
            label: "描述",
            prop: "description",
            type: "ueditor",
            component: 'avue-ueditor',
            action: "/api/blade-resource/oss/endpoint/put-file",
            propsHttp: {
              res: "data",
              url: "link"
            },
            options: {
              customConfig: {
                uploadImgMaxSize: 30 * 1024 *1024
              },
            },
            hide: true,
            row: true,
            span: 24
          },
        ]
      },
      data: [],
      ingredientsTableData: [],
      ingredientsOptions: [],
      ingredientsName: '',
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.food_add, false),
        viewBtn: false,
        delBtn: false,
        editBtn: this.vaildData(this.permission.food_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    unitContent() {
      return (unit) => {
        try {
          return `请输入${JSON.parse(unit).name}数（1 ${JSON.parse(unit).name} ${JSON.parse(unit).grams} 克）`
        } catch (e) {
          return ''
        }
      }
    },
    ingredientsKcal() {
      return (weight, kcal) => {
        if (kcal === 0 || weight === 0) {
          return 0
        }
        return weight / 100 * kcal
      }
    },
    foodKcal() {
      let kcal = 0
      this.ingredientsTableData.forEach(item => {
        const itemKcal = this.ingredientsKcal(item.weight, item.kcal)
        kcal += itemKcal
      })
      return kcal
    }
  },
  methods: {
    handleUnitCountChange(index, unitCount, unit) {
      const weight = JSON.parse(unit).grams * unitCount
      this.$set(this.ingredientsTableData[index], 'weight', weight)
    },
    handleIngredientsSelect(val, index) {
      this.$set(this.ingredientsTableData[index], 'id', val.id)
      this.$set(this.ingredientsTableData[index], 'unit', val.unit)
    },
    handleIngredientsChange(val, index) {
      if (val === '') {
        this.$set(this.ingredientsTableData[index], 'id', val.id)
        this.$set(this.ingredientsTableData[index], 'unit', val.unit)
      }
    },
    queryIngredientsAsync(queryString, cb) {
      const restaurants = this.ingredientsOptions;
      const results = queryString ? restaurants.filter(this.createIngredientsStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    createIngredientsStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().includes(queryString.toLowerCase()));
      };
    },
    handleAddItem() {
      this.ingredientsTableData.push({
        id: '',
        weight: 0,
        unit: '',
        kcal: 0,
        unitCount: '',
      })
    },
    handleRemoveItem(index) {
      this.ingredientsTableData.splice(index, 1)
    },
    rowSave(row, done, loading) {
      if (this.ingredientsTableData.length === 0) {
        this.$message.warning('请至少添加一种食材!')
        loading()
        return
      } else {
        try {
          this.ingredientsTableData.forEach(item => {
            if (item.id === '' || item.weight === '') {
              throw '请正确填写食材信息!'
            }
          })
        } catch (e) {
          this.$message.error(e)
          loading()
          return
        }
      }

      const foodIngredientsIdList = this.ingredientsTableData.map(item => item.id)
      if (foodIngredientsIdList.length !== this.ingredientsTableData.length || foodIngredientsIdList.includes('') || foodIngredientsIdList.includes(undefined)) {
        this.$message.warning('请正确填写食材信息！')
        loading()
        return;
      }

      row.foodIngredientsList = this.ingredientsTableData.map(item => {
        return {
          ingredientsId: item.id,
          grams: item.weight
        }
      })
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      if (this.ingredientsTableData.length === 0) {
        this.$message.warning('请至少添加一种食材!')
        loading()
        return
      } else {
        try {
          this.ingredientsTableData.forEach(item => {
            if (item.id === '' || item.weight === '') {
              throw '请正确填写食材信息!'
            }
          })
        } catch (e) {
          this.$message.error(e)
          loading()
          return
        }
      }

      const foodIngredientsIdList = this.ingredientsTableData.map(item => item.id)
      if (foodIngredientsIdList.length !== this.ingredientsTableData.length || foodIngredientsIdList.includes('') || foodIngredientsIdList.includes(undefined)) {
        this.$message.warning('请正确填写食材信息！')
        loading()
        return;
      }

      row.foodIngredientsList = this.ingredientsTableData.map(item => {
        return {
          ingredientsId: item.id,
          grams: item.weight
        }
      })
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleGetIngredientsOptions() {
      getSelect().then(res => {
        this.ingredientsOptions = res.data.data.map(item => {
          return {
            value: item.name,
            id: item.id,
            unit: item.unit,
            kcal: item.kcal,
          }
        })
      })
    },
    beforeOpen(done, type) {
      this.ingredientsTableData = []
      // this.handleGetIngredientsOptions()
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          const data = res.data.data
          this.form = data
          this.ingredientsTableData = data.foodIngredientsList.map(item => {
            let unit = ''
            let weight = item.grams
            this.ingredientsOptions.forEach(ingredients => {
              if (ingredients.id === item.ingredientsId) {
                unit = ingredients.unit
              }
            })
            return {
              id: item.ingredientsId,
              ingredientsName: item.ingredientsName,
              weight: weight,
              unit: unit,
              kcal: item.ingredientsKcal,
              unitCount: unit !== '' ? (weight / JSON.parse(unit).grams) : ''
            }
          })
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage){
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize){
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
      this.ingredientsTableData = []
      this.ingredientsOptions = []
      this.handleGetIngredientsOptions()
    }
  }
};
</script>

<style>
</style>
